/**
 * FileName: ArticleDaoImpl
 * Author:   Administrator
 * Date:     2/6/2024 3:30 PM
 * Description: 文章 数据层接口实现
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.t.blog.mongodb.dao.base.Impl;

import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.t.blog.mongodb.dao.base.IBaseDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * 〈一句话功能简述〉<br> 
 * 〈基础 mangodb 数据层接口实现〉
 *
 * @author Administrator
 * @create 2/6/2024 3:30 PM
 * @since 1.0.0
 */
public class BaseDao<T> implements IBaseDao<T> {

    private Class<T> clazz;

    public BaseDao() {
        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
        clazz = (Class<T>) type.getActualTypeArguments()[0];
    }


    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List find(Query query) {
        return mongoTemplate.find(query,clazz);
    }

    @Override
    public T findOne(String id) {
        Query query = new Query();
        query.addCriteria(new Criteria("_id").is(id));
        return mongoTemplate.findOne(query,clazz);
    }

    @Override
    public void insert(T entity) {
        mongoTemplate.insert(entity);
    }

    @Override
    public UpdateResult update(Query query, Update update) {
        return mongoTemplate.updateMulti(query, update, clazz);
    }

    @Override
    public DeleteResult delete(T entity) {
        return mongoTemplate.remove(entity);
    }
}
